`
You may sometimes find it useful to redirect the standard error
stream to a file, as we’ve done here, so you can log any errors that
occur during runtime. For example, the next example runs a non-
existent command lzl. This should generate bash errors that will be
written into the error.txt file.
$ lzl 2> error.txt
$ cat error.txt
bash: lz: command not found
Listing 1-13
Redirecting the standard error stream using its file descriptor number
Notice that you didn’t see the error on the screen because bash
sent the error to the file instead.
Next, let’s use the standard input stream. Run the following
command in the shell to supply the contents of output.txt as input to
the cat command:
$ cat < output.txt
Hello World!
Goodbye!
Listing 1-14
Redirecting standard input to the cat command
What if we wanted to redirect multiple lines to a command? Here
document redirection (<<) can help with this:
$ cat << EOF
Black Hat Bash
by No Starch Press
EOF
Black Hat Bash
by No Starch Press
Listing 1-15
A here document
In this example, we pass multiple lines as input to a command.
The EOF in this example acts as a delimiter marking the start and
end points of the input. Here document redirection treats the input as
if it were a separate file, preserving line breaks and whitespace.
The pipe operator (|) redirects the output of one command and
uses it as the input of another. For example, we could run the ls
command on the root directory and then use another command to
extract some data from it, as shown here:
$ ls -l / | grep "bin"
Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks